'''
Created on Sep 17, 2010

@author: diego


'''
import cv
import matplotlib
import matplotlib.pyplot as plt


import numpy
from SURFUtils import findPairsNaive, drawKeypoints, drawPoints,\
    getHomography

global figureNumber

def plotPoints(pointSet,color):
    global figureNumber
    color=str(color)+'o'
    plt.figure(figureNumber)
    for (x,y) in pointSet:
        plt.plot(x,y,color)

    
    figureNumber=figureNumber+1
            

def drawReferenceRectangle(bookTransform):
    cv.Line(bookTransform, (100, 100), (150, 100), cv.RGB(100, 0, 0))
    cv.Line(bookTransform, (100, 100), (100, 200), cv.RGB(0, 0, 100))
    cv.Line(bookTransform, (150, 100), (150, 200), cv.RGB(0, 100, 0))
    cv.Line(bookTransform, (100, 200), (150, 200), cv.RGB(100, 100, 100))
    cv.Line(bookTransform, (100, 100), (150, 200), cv.RGB(100, 100, 100))



if __name__ == '__main__':
    global figureNumber
    figureNumber=1
    srcMatchedKeypoints=[]
    dstMatchedKeypoints=[]
    storage=cv.CreateMemStorage(0)
    params=(0,3000,3,1)
    book1=cv.LoadImage("../resources/krishna2.jpg",cv.CV_LOAD_IMAGE_GRAYSCALE)
    book2=cv.LoadImage("../resources/krishna-rotated.jpg",cv.CV_LOAD_IMAGE_GRAYSCALE)
    match=cv.LoadImage("../resources/krishna2.jpg")
    match2=cv.LoadImage("../resources/krishna-rotated.jpg")
    
    srcSURF=cv.ExtractSURF(book1, None, storage, params)
    (srcKeyp,srcDesc)=srcSURF
    dstSURF=cv.ExtractSURF(book2, None, storage, params)
    (dstKeyp,dstDesc)=dstSURF
    
    matchedPairs=findPairsNaive(srcSURF,dstSURF)
    
    srcMatchedKeypoints=map((lambda x : x[0]),matchedPairs)
    dstMatchedKeypoints=map((lambda x : x[1]),matchedPairs)
    
    drawKeypoints(book1,srcKeyp)
    drawKeypoints(book2,dstKeyp)
    drawPoints(match, srcMatchedKeypoints)
    drawPoints(match2, dstMatchedKeypoints)
    
    cv.ShowImage("book keypoints", book1)
    cv.ShowImage("rotated book keypoints", book2)
    
    cv.ShowImage("matched src keypoints", match)
    cv.ShowImage("matched dst keypoints", match2)
#    plotPoints(srcMatchedKeypoints,'b')
#    plotPoints(dstMatchedKeypoints,'r')
    
    mapMatrix=getHomography(srcMatchedKeypoints, dstMatchedKeypoints)
    
    book1Warped=cv.CloneImage(book1)
    bookTransform=cv.CreateMat(480,640,cv.CV_32FC3)
    bookTransformed=cv.CloneMat(bookTransform)
    
    drawReferenceRectangle(bookTransform)
    
    cv.WarpPerspective(bookTransform, bookTransformed,mapMatrix) 
    cv.WarpPerspective(book1, book1Warped,mapMatrix)
    
    cv.ShowImage("transform", bookTransform)
    cv.ShowImage("bookTransofrmed", bookTransformed)
    cv.ShowImage("book1Warped", book1Warped)
#    plt.show()
    cv.WaitKey(0)
    
#    compare_desc(srcDesc, dstDesc)
#        for ((x, y), laplacian, size, dir, hessian) in keypoints:
#            print "x=%d y=%d laplacian=%d size=%d dir=%f hessian=%f" % (x, y, laplacian, size, dir, hessian)
#    cv.Circle(frame, (x,y), size, (200,50,50))
    

